<template>
  <div class="container-wrap showEdit">
    <template v-if="isEdit">
        <Validator ref="validatorRef" v-model="content" :rules="rule" :style="{ width: width }">
          <el-date-picker
            ref="inputRef"
            v-model="content"
            style="width: 100%"
            v-bind="$attrs"
            @blur="toPreview()"
          ></el-date-picker>
        </Validator>
    </template>

    <span v-else class="desc">
      <StringView v-if="desc" :str="desc" :len="descLength" />
      <StringView v-else :str="row[inputKey]" :len="descLength" />
      <el-icon v-if="!onlyRead" :size="18" class="edit" @click="toEdit">
        <edit></edit>
      </el-icon>
    </span>
  </div>
</template>

<script lang="ts" setup>
import { ObjTy } from '~/common'
import Validator from './components/validator.vue'
import StringView from '@/components/StringView/index.vue'

const props = defineProps({
  row: {
    type: Object,
    default() {
      return {}
    }
  },
  onlyRead: {
    type: Boolean,
    default: false
  },
  inputType: {
    type: String,
    default: 'text'
  },
  inputPlaceholder: {
    type: String,
    default: '请输入内容'
  },
  inputKey: {
    type: String,
    default: ''
  },

  /** 组件属性 */
  rule: {
    type: Array,
    default: () => []
  },
  desc: {
    type: [String, Number],
    default: ''
  },
  descLength: {
    type: Number,
    default: 100
  },
  width: {
    type: [String, Number],
    default: 'auto'
  }
})
const isEdit = ref(false)
const content = ref()
const inputRef = ref()
const validatorRef = ref()
const emits = defineEmits(['update-value'])
const resetVal = () => {
  if (props.desc) {
    content.value = props.desc
  } else {
    content.value = props.row[props.inputKey]
  }
}

const toFocus = async () => {
  if (isEdit) {
    await nextTick()
    if (inputRef.value?.focus) {
      inputRef.value.focus()
    }
  }
}
const toEdit = () => {
  isEdit.value = true
  resetVal()
  toFocus()
}
const toPreview = () => {
  validatorRef.value.validate().then(() => {
    let obj: ObjTy = {}
    obj[props.inputKey] = content.value
    emits('update-value', obj)
    isEdit.value = false
  })
}
</script>
<style lang="scss" scoped>
@use './styles/field.scss';
</style>
